package com.testyourshell.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class BaseDAOImpl<Entity extends Serializable> implements
		BaseDAO<Entity> {

	@Autowired
	protected SessionFactory sessionFactory;

	private Class<Entity> clazz = getEntityClass();

	@SuppressWarnings("unchecked")
	@Override
	public List<Entity> findAll() {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"FROM " + clazz.getCanonicalName());
		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Entity findById(final Long id) {
		return (Entity) sessionFactory.getCurrentSession().get(clazz, id);
	}

	@Override
	public void create(Entity createdEntity) {
		sessionFactory.getCurrentSession().persist(createdEntity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Entity update(Entity updatedEntity) {
		return (Entity) sessionFactory.getCurrentSession().merge(updatedEntity);
	}

	@Override
	public void delete(Entity deletedEntity) {
		sessionFactory.getCurrentSession().delete(deletedEntity);
	}

	protected abstract Class<Entity> getEntityClass();

}
